package com.jin.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 远程调用的时候，将请求头的内容同步到新的请求头里（Feign远程调用的时候会新建里Request）
 */
@Configuration
public class GuliFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1.RequestContextHolder拿到刚进来的这个请求
                //RequestContextHolder这个是spring提供的，底层实际上是threadLocal
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                System.out.println("RequestTemplate线程..."+Thread.currentThread().getId());
                if(requestAttributes!=null){
                    HttpServletRequest request = requestAttributes.getRequest();//这是老的请求
                    //同步请求头数据，Cookie
                    String cookie = request.getHeader("Cookie");
                    //给新请求同步了老请求的cookie
                    template.header("Cookie", cookie);
                }
            }
        };
    }
}
